﻿using System;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Kaio.Mvc.Routing;
using MvcForum.Net.Bussiness;
using MvcForum.Net.Bussiness.Jobs;

namespace MvcForum.Net
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        /* private static IScheduler _scheduler;

         public static IScheduler Scheduler
         {
             get { return _scheduler; }
         }
         * 
         * 
         * 
 */



        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {

            var section = (MvcRouteConfigurationSection)ConfigurationManager.GetSection("RouteConfiguration");

            routes.MapRouteFromXml(section, null);

        }

        protected void Application_End()
        {
            MvcForumScheduler.Instant.Shutdown();

            log4net.LogManager.Shutdown();

        }

        protected void Application_Start()
        {



            #region Logging Start


            //string l4net = Server.MapPath("~/log4net.config");

            log4net.Config.XmlConfigurator.Configure();

            /*  log4net.Repository.Hierarchy.Hierarchy hier = log4net.LogManager.GetRepository() as log4net.Repository.Hierarchy.Hierarchy;

              if (hier != null)
              {
                  //get ADONetAppender
                  log4net.Appender.AdoNetAppender adoAppender =
                    (log4net.Appender.AdoNetAppender)hier.GetLogger("ADONetAppender",
                      hier.LoggerFactory).GetAppender("ADONetAppender");
                  if (adoAppender != null)
                  {
                      adoAppender.ConnectionString =
                        System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
                      adoAppender.ActivateOptions(); //refresh settings of appender
                  }

              }*/


            //log.Info("Application Start");

            /* string l4net = Server.MapPath("~/log4net.config");
             log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(l4net));

             */


            #endregion



            #region Run Ok

            // First we must get a reference to a scheduler
            /* NameValueCollection properties = new NameValueCollection();
             properties["quartz.scheduler.instanceName"] = "PriorityExampleScheduler";
             // Set thread count to 1 to force Triggers scheduled for the same time to 
             // to be ordered by priority.
             properties["quartz.threadPool.threadCount"] = "1";
             properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
             properties["quartz.jobStore.type"] = "Quartz.Simpl.RAMJobStore, Quartz";*/

            /*
            ISchedulerFactory sf = new StdSchedulerFactory();
            IScheduler sched = sf.GetScheduler();

            IJobDetail job = JobBuilder.Create<SendEmail>()
               .WithIdentity("job1", "group1")
               .Build();

            ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                                                      .WithIdentity("trigger1", "group1")
                                                      .WithCronSchedule("0/30 * * * * ?")
                                                      .Build();

            sched.ScheduleJob(job, trigger);
            sched.Start();
*/

            MvcForumScheduler.Start();

            #endregion


            /*var properties = new NameValueCollection();
            properties["quartz.scheduler.instanceName"] = "XmlConfiguredInstance";

            // set thread pool info
            properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool";
            properties["quartz.threadPool.threadCount"] = "10";
            properties["quartz.threadPool.threadPriority"] = "Normal";

            // job initialization plugin handles our xml reading, without it defaults are used
            properties["quartz.plugin.xml.type"] = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin";
            properties["quartz.plugin.xml.fileNames"] = "~/quartz.xml";

            ISchedulerFactory sf = new StdSchedulerFactory(properties);*/
            /* ISchedulerFactory sf = new StdSchedulerFactory();

            
             _scheduler = sf.GetScheduler();*/

            /*   var trigger = TriggerBuilder.Create().WithIdentity("SendEmailTrigger", "SendEmailGroup")
                                .WithCronSchedule("0/1 * * ?")
                                .Build() as ICronTrigger;


               var job = JobBuilder.Create<SendEmail>().WithIdentity("SendEmailJob", "SendEmailGroup").Build();



              _scheduler .ScheduleJob(job, trigger);
   */


            /*_scheduler.Start();*/
            /* ISchedulerFactory factory = new StdSchedulerFactory();
             // get a scheduler 
             _scheduler = factory.GetScheduler();
             // start the scheduler 
             _scheduler.Start();*/

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }


        //private static readonly Regex wwwRegex = new Regex(@"www\.(?<mainDomain>.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);

        protected void Application_BeginRequest(Object sender, EventArgs e)
        {


            if (Request.IsSecureConnection)
            {
                string redirectUrl = Request.Url.ToString().Replace("https:", "http:");
                Response.Redirect(redirectUrl);
            }

            // redirect http --> https
            /* if (!Request.IsLocal && !Request.IsSecureConnection)
             {
                 string redirectUrl = Request.Url.ToString().Replace("http:", "https:");
                 Response.Redirect(redirectUrl);
             }*/

            /*string hostName = Request.Headers["x-forwarded-host"];
            hostName = string.IsNullOrEmpty(hostName) ? Request.Url.Host : hostName;
          

            Match match = wwwRegex.Match(hostName);
            if (match.Success)
            {
                //string mainDomain = match.Groups["mainDomain"].Value;
                /* var builder = new UriBuilder(Request.RawUrl)
                 {
                   Host = mainDomain
                 };#1#

                var _rawUrl = Request.RawUrl;
                string redirectUrl = string.Format("//:{0}{1}", Request.Url.Host, _rawUrl);
                Response.Clear();
                Response.StatusCode = 301;
                Response.StatusDescription = "Moved Permanently";
                Response.AddHeader("Location", redirectUrl);
                Response.End();
            }*/


          /*  try
            {
                const string auth_param_name = "SessionId";
                string auth_cookie_name = FormsAuthentication.FormsCookieName;

                if (HttpContext.Current.Request.Form[auth_param_name] != null)
                {
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
                {
                    UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
                }

            }
            catch (Exception)
            {
                Response.StatusCode = 500;
                Response.Write("Error Initializing Forms Authentication");
            }*/
        }


        void UpdateCookie(string cookie_name, string cookie_value)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
            if (cookie == null)
            {
                cookie = new HttpCookie(cookie_name);
                HttpContext.Current.Request.Cookies.Add(cookie);
            }
            cookie.Value = cookie_value;
            HttpContext.Current.Request.Cookies.Set(cookie);
        }

        public override string GetVaryByCustomString(HttpContext context, string arg)
        {
            if (arg == "OutputCacheKey")
            {
                return ForumContext.OutputCacheKey;
            }

            return base.GetVaryByCustomString(context, arg);

        }

    }
}